<?php

namespace polymerize\user\module\user;

use app\common\InstanceTrait;
use app\common\LoginType;
use app\common\SmsType;
use app\model\User as UserModel;
use app\model\UserToken;
use support\Cache;
use support\Redis;

class BindMobile
{
    use InstanceTrait;

    /**
     * 绑定手机号
     *
     * @param int    $uid
     * @param string $mobile
     * @param int    $smsCode
     * @param string $token
     * @return array
     */
    public function bindMobile(int $uid, string $mobile, int $smsCode, string $token): array
    {
        $smsKey = 'SMS_CODE_' . md5($mobile . SmsType::SMS_CODE_BIND_MOBILE->value);
        if ($smsCode != Cache::get($smsKey)) return ['code' => 400, 'msg' => '短信验证码错误', 'data' => []];

        $where[]   = ['id', '=', $uid];
        $field     = 'id,mobile,status,create_time,avatar,login_type,ref,password';
        $user_info = UserModel::where($where)->field($field)->find();
//        if ($user_info['mobile']) return ['code' => 400, 'msg' => '当前账号已经绑定手机号了', 'data' => []];

        $where2[]        = ['mobile', '=', $mobile];
        $where2[]        = ['id', '<>', $uid];
        $mobileOtherUser = UserModel::getOne($where2);
        if ($mobileOtherUser) return ['code' => 400, 'msg' => '该手机号已被其他账号绑定', 'data' => []];

        $update = [
            'mobile' => $mobile,
            'u_time' => myDate(),
        ];
        (new UserModel())->where('id', $uid)->update($update);// 把手机号的用户干掉
        (new UserToken())->where('uid', $uid)->delete();      // 把手机号的用户Token干掉
        Cache::delete($smsKey);
        Redis::set(APP_TOKEN_LOGIN . $token, [], 'EX', 1, 1);

        //设置新的token
        $newToken      = UserToken::loginToken($user_info, LoginType::LOGIN_TYPE_PHONE->value);
        $data['token'] = $newToken['token'] ?? '';
        $data['uid'] = $uid;

        return ['code' => 200, 'msg' => '', 'data' => $data];
    }
}
